﻿using Admin.NET.Core.Service;
using Admin.NET.Application.Const;
using Admin.NET.Application.Entity;
using Microsoft.AspNetCore.Http;
using Furion.DatabaseAccessor;
using Magicodes.ExporterAndImporter.Core;
using Magicodes.ExporterAndImporter.Excel;
using Microsoft.AspNetCore.Components.Forms;
using System.Runtime.InteropServices;
namespace Admin.NET.Application;
/// <summary>
/// 课程服务
/// </summary>
[ApiDescriptionSettings(ApplicationConst.GroupName, Order = 100)]
public class KechengService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<SysFile> _fileRep;
    private readonly SqlSugarRepository<Teacher> _teacherRep;
    private readonly SqlSugarRepository<XuankeTask> _xuankeTaskRep;
    private readonly SqlSugarRepository<Kecheng> _rep;
    private readonly UserManager _userManager;

    public KechengService(SqlSugarRepository<Kecheng> rep, SqlSugarRepository<SysFile> fileRep, SqlSugarRepository<Teacher> teacherRep, SqlSugarRepository<XuankeTask> xuankeTaskRep, UserManager userManager)
    {
        _rep = rep;
        _fileRep = fileRep;
        _teacherRep = teacherRep;
        _xuankeTaskRep = xuankeTaskRep;
        _userManager= userManager;
    }

    /// <summary>
    /// 分页查询课程
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Page")]
    public async Task<SqlSugarPagedList<KechengOutput>> Page(KechengInput input)
    {
        var query = _rep.AsQueryable()
            .WhereIF(!string.IsNullOrWhiteSpace(input.SearchKey), u =>
                u.Name.Contains(input.SearchKey.Trim())
                || u.Description.Contains(input.SearchKey.Trim())
            )
            .WhereIF(input.XuankeTaskId>0, u => u.XuankeTaskId == input.XuankeTaskId)
            .WhereIF(!string.IsNullOrWhiteSpace(input.Name), u => u.Name.Contains(input.Name.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Description), u => u.Description.Contains(input.Description.Trim()))
            .WhereIF(input.TeacherId>0, u => u.TeacherId == input.TeacherId)
            //处理外键和TreeSelector相关字段的连接
            .LeftJoin<XuankeTask>((u, xuanketaskid) => u.XuankeTaskId == xuanketaskid.Id )
            .LeftJoin<Teacher>((u, xuanketaskid, teacherid) => u.TeacherId == teacherid.Id )
            .OrderBy(u => u.CreateTime)
            .Select((u, xuanketaskid, teacherid) => new KechengOutput
            {
                Id = u.Id,
                XuankeTaskId = u.XuankeTaskId, 
                XuankeTaskIdName = xuanketaskid.Name,
                Name = u.Name,
                Description = u.Description,
                TeacherId = u.TeacherId, 
                TeacherIdName = teacherid.Name,
                Address = u.Address,
                ZhaoshengRenshu = u.ZhaoshengRenshu,
                LvquRenshu = u.LvquRenshu,
                Remark = u.Remark,
                BanjiLimit = u.BanjiLimit,
                CreateUserName = u.CreateUserName,
                UpdateUserName = u.UpdateUserName,
            });
        return await query.ToPagedListAsync(input.Page, input.PageSize);
    }

    /// <summary>
    /// 增加课程
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Add")]
    public async Task<long> Add(AddKechengInput input)
    {
        var entity = input.Adapt<Kecheng>();
        await _rep.InsertAsync(entity);
        return entity.Id;
    }

    /// <summary>
    /// 删除课程
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Delete")]
    public async Task Delete(DeleteKechengInput input)
    {
        var entity = await _rep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
        //await _rep.FakeDeleteAsync(entity);   //假删除
        await _rep.DeleteAsync(entity);   //真删除
    }

    /// <summary>
    /// 更新课程
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Update")]
    public async Task Update(UpdateKechengInput input)
    {
        var entity = input.Adapt<Kecheng>();
        await _rep.AsUpdateable(entity).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();
    }

    /// <summary>
    /// 获取课程
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpGet]
    [ApiDescriptionSettings(Name = "Detail")]
    public async Task<Kecheng> Detail([FromQuery] QueryByIdKechengInput input)
    {
        return await _rep.GetFirstAsync(u => u.Id == input.Id);
    }

    /// <summary>
    /// 获取选课任务列表
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [ApiDescriptionSettings(Name = "XuankeTaskXuankeTaskIdDropdown"), HttpGet]
    public async Task<dynamic> XuankeTaskXuankeTaskIdDropdown()
    {
        return await _rep.Context.Queryable<XuankeTask>()
                .Select(u => new
                {
                    Label = u.Name,
                    Value = u.Id
                }
                ).ToListAsync();
    }
    /// <summary>
    /// 获取上课老师列表
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [ApiDescriptionSettings(Name = "TeacherTeacherIdDropdown"), HttpGet]
    public async Task<dynamic> TeacherTeacherIdDropdown()
    {
        return await _rep.Context.Queryable<Teacher>()
                .Select(u => new
                {
                    Label = u.Name,
                    Value = u.Id
                }
                ).ToListAsync();
    }

    /// <summary>
    /// 导入课程
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [UnitOfWork]
    [ApiDescriptionSettings(Name = "Import")]
    public async Task<string> Import(ImportKechengInput input)
    {
        var file = _fileRep.GetById(input.FileId);
        var filePath = App.WebHostEnvironment.WebRootPath;
        filePath = System.IO.Path.Combine(filePath, file.FilePath);
        filePath = System.IO.Path.Combine(filePath, file.Id.ToString());
        filePath += file.Suffix;

        var xuankeTask = await _xuankeTaskRep.GetByIdAsync(input.XuankeTaskId);
        if(xuankeTask == null)
        {
            throw Oops.Oh("选课任务必选。");
        }

        IImporter importer = new ExcelImporter();
        var res = await importer.Import<KechengImportDto>(filePath);
        foreach (var item in res.Data)
        {
            //var student = item.Adapt<Student>();
            var kecheng = await _rep.AsQueryable().Where(p => p.Name == item.Name && p.XuankeTaskId == input.XuankeTaskId).FirstAsync();
            if (kecheng == null)
            {
                kecheng = new Kecheng();
                kecheng.Name = item.Name;
                kecheng.XuankeTaskId = input.XuankeTaskId;
            }

            //序号	课程名称	任课教师	上课地点	备注	招生人数
            var teacher = await _teacherRep.AsQueryable().Where(p => p.Name == item.TeacherIdName).FirstAsync();
            if(teacher != null)
                kecheng.TeacherId = teacher.Id;
            
            kecheng.Address = item.Address;
            kecheng.Remark = item.Remark;
            kecheng.ZhaoshengRenshu = item.ZhaoshengRenshu;
            kecheng.Description = item.Description;
            kecheng.BanjiLimit = item.BanjiLimit;

            if (kecheng.Id != 0)
                await _rep.UpdateAsync(kecheng);
            else
                await _rep.InsertAsync(kecheng);
        }
        return string.Format("成功导入{0}条记录", res.Data.Count);
    }

    /// <summary>
    /// 根据教师获取课程列表
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "ListByTeacherId")]
    public async Task<List<KechengOutput>> ListByTeacherId()
    {
        var userId = _userManager.UserId;
        var query = _rep.AsQueryable()
            .Where(u => u.TeacherId == userId)
            .LeftJoin<XuankeTask>((u, xuanketaskid) => u.XuankeTaskId == xuanketaskid.Id)
            .LeftJoin<Teacher>((u, xuanketaskid, teacherid) => u.TeacherId == teacherid.Id)
            .Where((u, xuanketaskid) => xuanketaskid.Active == true)
            .OrderBy(u => u.CreateTime)
            .Select((u, xuanketaskid, teacherid) => new KechengOutput
            {
                Id = u.Id,
                XuankeTaskId = u.XuankeTaskId,
                XuankeTaskIdName = xuanketaskid.Name,
                Name = u.Name,
                Description = u.Description,
                TeacherId = u.TeacherId,
                TeacherIdName = teacherid.Name,
                Address = u.Address,
                ZhaoshengRenshu = u.ZhaoshengRenshu,
                LvquRenshu = u.LvquRenshu,
                Remark = u.Remark,
                CreateUserName = u.CreateUserName,
                UpdateUserName = u.UpdateUserName,
            });
        return await query.ToListAsync();
    }
}

